package com.ccp.dev.workflow.controller;

import com.ccp.dev.core.basic.annotion.Action;
import com.ccp.dev.core.basic.annotion.ActionExecOrder;
import com.ccp.dev.core.basic.consts.UrlConstants;
import com.ccp.dev.core.basic.internationalization.SysBaseController;
import com.ccp.dev.core.basic.model.SysAuditModelType;
import com.ccp.dev.core.basic.response.ResultData;
import com.ccp.dev.core.basic.web.query.QueryFilter;
import com.ccp.dev.core.util.*;
import com.ccp.dev.core.util.log.SysAuditThreadLocalHolder;
import com.ccp.dev.form.model.FormField;
import com.ccp.dev.form.service.FormFieldService;
import com.ccp.dev.workflow.model.Identity;
import com.ccp.dev.workflow.service.IdentityService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * ClassDescribe
 *
 * @author: fanruiqi
 * Date: 2019-08-29
 * Since:1
 * To change this template use File | Settings | File Templates.
 */

@Controller
@RequestMapping(UrlConstants.PROJECT_ROOT + UrlConstants.PROJECT_MODULE_WORKFLOW + "/identity")
public class IdentityController extends SysBaseController {
    private static final Logger logger = LoggerFactory.getLogger(IdentityService.class);

    @Resource
    private IdentityService identityService;
    @Resource
    private FormFieldService formFieldService;


    /**
     * 添加页面-弹窗  （表单模块List）
     * 编辑页面-弹窗  （表单模块List）
     *
     * @return 页面路径
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + UrlConstants.MODULE_FUNCTION_ADD_UPDATE)
    @Action(description = "流水号添加或编辑页面弹窗跳转",ownermodel = SysAuditModelType.FORM_MANAGEMENT, exectype = "页面跳转日志")
    public String addSer(HttpServletRequest request, Model model) {
        this.viewAddOrEdit(request,model);
        return getAutoView();
    }

    /**
     * 添加页面-弹窗  （流程模块commonList）
     * 编辑页面-弹窗  （流程模块commonList）
     *
     * @return 页面路径
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/commonAdd")
    @Action(description = "流水号添加或编辑页面弹窗跳转",ownermodel = SysAuditModelType.PROCESS_AUXILIARY,
            exectype = "页面跳转日志")
    public String viewCommonAdd(HttpServletRequest request, Model model) {
        this.viewAddOrEdit(request,model);
        return getAutoView();
    }

    /**
     * 提取公共方法，编辑页面回显数据
     * @param request
     * @param model
     */
    private void viewAddOrEdit(HttpServletRequest request, Model model) {
        String id = RequestUtil.getString(request, "id");
        //编辑页面回显
        if (StringUtil.isNotEmpty(id)) {
            Identity identity = identityService.getOneById(id);
            model.addAttribute("identity", identity);
        }
    }

    /**
     * 跳转流水号页面 弹窗（表单模块）
     *
     * @return 弹窗路径
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + UrlConstants.MODULE_FUNCTION_LIST)
    @Action(description = "流水号页面弹窗跳转",ownermodel = SysAuditModelType.FORM_MANAGEMENT,
            exectype = "页面跳转日志")
    public String serNumber(HttpServletRequest request, Model model) {
        String parentName = RequestUtil.getString(request, "parentName");
        model.addAttribute("parentName", parentName);
        return getAutoView();
    }

    /**
     * 跳转流水号页面 （流程模块）
     *
     * @return 页面路径
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/commonList")
    @Action(description = "流水号页面跳转",ownermodel = SysAuditModelType.PROCESS_AUXILIARY,
            exectype = "页面跳转日志")
    public String viewMyList() {
        return getAutoView();
    }

    /**
     * 明细页面-弹窗
     *
     * @param request
     * @param model
     * @return 弹窗路径
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + UrlConstants.MODULE_FUNCTION_GET)
    @Action(description = "流水号明细页面弹窗跳转",ownermodel = SysAuditModelType.PROCESS_AUXILIARY,
            detail = "流水号明细页面弹窗跳转成功")
    public String get(HttpServletRequest request, Model model) {
        String id = RequestUtil.getString(request, "id");
        Identity identity = identityService.getOneById(id);
        model.addAttribute("identity", identity);
        return getAutoView();
    }

    /**
     * 跳转页面importXml
     *
     * @return 页面路径
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/importXml")
    @Action(description = "导入流水号XML页面弹窗跳转",ownermodel = SysAuditModelType.PROCESS_AUXILIARY,
            exectype = "页面跳转日志")
    public String viewImportXml() {
        return getAutoView();
    }

    /**
     * 获取流水号的所有数据
     *
     * @param request 请求
     */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_LIST)
    @Action(description = "流水号所有数据查询",ownermodel = SysAuditModelType.PROCESS_AUXILIARY,
            detail = "流水号所有数据查询成功")
    @ResponseBody
    public ResultData list(HttpServletRequest request) {
        QueryFilter queryFilter = new QueryFilter(request, true);
        List<Identity> list = identityService.queryList(queryFilter);
        return getResultDataSuccess("operation.success", queryFilter.getPageBean().getTotalCount(), list);
    }

    /**
     * 根据alias查询流水号生成明细
     *
     * @param request
     * @return 返回数据
     */
    @RequestMapping("/getByAlias")
    @Action(description = "根据alias查询流水号生成明细",ownermodel = SysAuditModelType.PROCESS_AUXILIARY,
            detail = "根据<#assign ent=RequestUtil.getString(request, \"alias\") ${ent}查询流水号生成明细 />")
    public ResultData getByAlias(HttpServletRequest request)  {
        String alias = RequestUtil.getString(request, "alias");
        Identity identity = identityService.getByAlias(alias);
        return getResultDataSuccess("operation.success", identity);
    }

    /**
     * 根据alias查询下一个流水号
     *
     * @param request
     * @return 返回数据
     */
    @RequestMapping("/getNext")
    @Action(description = "根据alias查询下一个流水号",ownermodel = SysAuditModelType.PROCESS_AUXILIARY,
            detail = "根据<#assign ent=RequestUtil.getString(request, \"alias\") ${ent}查询下一个流水号<#if suceess>成功<#else>失败</#if>")
    public ResultData getById(HttpServletRequest request) {
        String alias = RequestUtil.getString(request, "alias");
        String rtn = identityService.nextId(alias);
        Map<String, Object> map = new HashMap<String, Object>(2);
        if (rtn != null) {
            map.put("rtn", rtn);
            map.put("success", 1);
            SysAuditThreadLocalHolder.putParamerter("success",true);
            return getResultDataSuccess("operation.success", map);
        } else {
            map.put("success", 0);
            SysAuditThreadLocalHolder.putParamerter("success",false);
            return getResultDataError("operation.failure");
        }
    }

    /**
     * 添加或保存流水号
     *
     * @param identity 流水号对象
     * @return 返回结果
     */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_ADD_UPDATE)
    @Action(description = "添加或保存流水号",ownermodel = SysAuditModelType.PROCESS_AUXILIARY,
            detail = "流水号<#if save>保存成功<#else>添加或保存操作失败</#if>")
    @ResponseBody
    public ResultData save(@RequestBody Identity identity) {
        //判断name和alias的字节长度小于数据库的字节长度
        String lengthMsg = identityService.nameAndAlias(identity.getAlias(), identity.getIdentityName());
        if(lengthMsg!=null){
            return getResultDataError(lengthMsg);
        }
        //判断别名是否重复
        boolean isAliasExisted = identityService.isAliasExisted(identity.getAlias(), identity.getId());
        if (isAliasExisted) {
            return getResultDataError("dataSource.save.aliasWarning");
        }
        //执行保存操作
        int count = identityService.addOrUpdate(identity);
        if (count > 0) {
            SysAuditThreadLocalHolder.putParamerter("save",true);
            return getResultDataSuccess("operation.success");
        } else {
            SysAuditThreadLocalHolder.putParamerter("save",false);
            return getResultDataError("operation.failure");
        }
    }


    /**
     * 删除流水号生成
     *
     * @param request
     * @return 返回结果
     */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_DELETE)
    @Action(description = "删除流水号生成",ownermodel = SysAuditModelType.PROCESS_AUXILIARY,execOrder = ActionExecOrder.BEFORE,
            detail = "流水号删除<#if success>成功<#else>失败</#if>")
    @ResponseBody
    public ResultData del(HttpServletRequest request) {
        String[] ids = RequestUtil.getStringAryByStr(request, "ids");
        //未删除的流水号，因为被引用所以存在依赖导致无法被删除
        List<String> serialNumList = new ArrayList<String>();
        //删除成功的流水号
        List<String> delSerialNums = new ArrayList<String>();
        try {
            for (String id : ids) {
                Identity identity = identityService.getOneById(id);
                //依赖约束判断是否删除
                if (identity != null) {
                    List<FormField> formFields = formFieldService.queryBySerialNum(identity.getAlias());
                    if (formFields != null && formFields.size() > 0) {
                        serialNumList.add(identity.getAlias());
                    } else {
                        delSerialNums.add(identity.getAlias());
                        identityService.delById(identity.getId());
                    }
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
            return getResultDataError("delete.failure");
        }
        if (serialNumList.size() > 0 && delSerialNums.size() > 0) {
            //既有删除失败的，也有删除成功的
            Map<String, String> map = new HashMap<>(2);
            //删除成功的流水号
            map.put("delSerialNums", delSerialNums.toString());
            //删除失败的流水号
            map.put("serialNumList", serialNumList.toString());
            SysAuditThreadLocalHolder.putParamerter("success",false);
            return getResultDataError("identity.delete.same.failure", 2, map);
        } else if (delSerialNums.size() > 0) {
            //仅有删除成功的
            SysAuditThreadLocalHolder.putParamerter("success",true);
            return getResultDataSuccess("identity.delete.success");
        } else {
            //仅有删除失败的
            Map<String, String> map = new HashMap<>(1);
            //删除成功的流水号
            map.put("serialNumList", serialNumList.toString());
            SysAuditThreadLocalHolder.putParamerter("success",false);
            return getResultDataError("identity.delete.failure",1,map);
        }
    }

    /**
     * 导入流水号XML
     *
     * @param request
     * @return 返回结果
     * @throws Exception
     */
    @RequestMapping("/importXml")
    @Action(description = "导入流水号XML",ownermodel = SysAuditModelType.PROCESS_AUXILIARY,
            detail = "流水号导入<#if success>成功<#else>失败</#if>")
    @ResponseBody
    public ResultData importXml(MultipartHttpServletRequest request) {
        MultipartFile file = request.getFile("file");
        try {
            identityService.importXml(file.getInputStream());
            SysAuditThreadLocalHolder.putParamerter("success",true);
            return getResultDataSuccess("file.importXml.success");
        } catch (Exception e) {
            logger.error(e.getMessage());
            SysAuditThreadLocalHolder.putParamerter("success",false);
            return getResultDataError("file.importXml.failure",1,e.getMessage());
        }
    }

    /**
     * 导出流水号XML
     *
     * @param request
     * @return 返回结果
     * @throws Exception
     */
    @RequestMapping("/exportXml")
    @Action(description = "导出流水号XML",ownermodel = SysAuditModelType.PROCESS_AUXILIARY,
            detail = "流水号导出<#if success>成功<#else>失败</#if>")
    public void exportXml(HttpServletRequest request, HttpServletResponse response) {
        String strXml = null;
        String fileName = null;
        String[] tableIds = RequestUtil.getStringAryByStr(request, "tableIds");
        List<Identity> list = identityService.queryAll();
        try {
            if (BeanUtils.isEmpty(tableIds)) {
                if (BeanUtils.isNotEmpty(list)) {
                    strXml = identityService.exportXml(list);
                    fileName = "全部流水号记录_" + DateFormatUtil.getNowByString("yyyyMMddHHmmdd") + ".xml";
                }
            } else {
                strXml = identityService.exportXml(tableIds);
                fileName = DateFormatUtil.getNowByString("yyyyMMddHHmmdd")
                        + ".xml";
                if (tableIds.length == 1) {
                    Identity identity = identityService.getOneById(tableIds[0]);
                    fileName = identity.getIdentityName() + "_" + fileName;
                } else if (tableIds.length == list.size()) {
                    fileName = "全部流水号记录_" + fileName;
                } else {
                    fileName = "多条流水号记录_" + fileName;
                }
            }
            FileUtil.downLoad(request, response, strXml, fileName);
            SysAuditThreadLocalHolder.putParamerter("success",true);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            SysAuditThreadLocalHolder.putParamerter("success",false);
        }
    }
}
